package com.guohong.filter;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class AccessFilter extends ZuulFilter {
	private static Logger logger = LoggerFactory.getLogger(AccessFilter.class);

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		logger.info(request.getMethod() + "," + request.getRequestURL().toString());
		
		String requestUrl = request.getRequestURL().toString();
		if (!requestUrl.contains("/login")) {
			Object accessToken = request.getHeader("accessToken");
			
			if (null == accessToken) {
				logger.warn("accessToken is empty");
				ctx.setSendZuulResponse(false); // false,zuul过滤该请求，不进行路由，返回错误码
				ctx.setResponseStatusCode(401);
				return null;
			}

			logger.info("access token is ok");
		}

		return null;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public String filterType() {
		return "pre";
	}

}
